<?php


namespace KukePay\Ali\Payment\Unifiedorder;


use KukePay\Ali\Payment\Kernel\ConfigFactory;
use KukePay\Ali\Payment\Kernel\SignFactory;
use KukePay\ExceptionHandler;
use KukePay\Kernel\Factory;

class Application extends Factory
{

    private static $interface;

    private $config;

    private $commonConfigs;

    private $sign;

    /**
     * @param ConfigFactory $config
     * @return Application
     */
    public static function getInterface(ConfigFactory $config)
    {
        if (!isset(self::$interface)) {
            self::$interface = new self($config);
        }
        return self::$interface;
    }

    /**
     * Application constructor.
     * @param ConfigFactory $config
     */
    public function __construct(ConfigFactory $config)
    {
        $this->config = $config;
        $this->sign = SignFactory::getInterface();
        parent::__construct();
    }

    /**
     * @param $params
     * @param $method
     * @param array $extend
     * @return $this
     * @throws ExceptionHandler
     */
    public function set($params, $method, $extend = [])
    {
        //组装参数
        $commonConfigs = [
            'app_id' => $this->config->getAppId(),
            'method' => $method,
            'format' => $this->config->getFormat(),
            'return_url' => $params['return_url'] ?? $this->config->getReturnUrl(),
            'charset' => $this->config->getCharset(),
            'sign_type' => $this->config->getSignType(),
            'timestamp' => date('Y-m-d H:i:s'),
            'version' => $this->config->getVersion(),
            'notify_url' => $params['notify_url'] ?? $this->config->getNotifyUrl(),
            'biz_content' => json_encode($params),
        ];

        $commonConfigs = array_merge($commonConfigs, $extend);

        if (empty($this->config->getRsaPrivateKey())) throw new ExceptionHandler('请传入私钥');
        //获取签名
        $commonConfigs['sign'] = $this->sign->generateSign($commonConfigs, $this->config->getRsaPrivateKey(), $commonConfigs['sign_type']);

        $this->commonConfigs = $commonConfigs;
        return $this;
    }

    /**
     * 发送http请求
     * @return string
     */
    public function send()
    {
        $response = $this->request->post($this->config->getUri(), $this->commonConfigs)->getBody()->getContents();
        $response = iconv('GBK', 'UTF-8', $response);
        return json_decode($response, true);
    }


    /**
     * 建立请求，以表单HTML形式构造（默认）
     * @return string
     */
    public function buildRequestForm()
    {
        $para_temp = $this->commonConfigs;
        $sHtml = "正在跳转至支付页面...<form id='alipaysubmit' name='alipaysubmit' action='" . $this->config->getUri() . "?charset=" . $this->config->getCharset() . "' method='POST'>";
        foreach ($para_temp as $key => $val) {
            if (false === $this->sign->checkEmpty($val)) {
                $val = str_replace("'", "&apos;", $val);
                $sHtml .= "<input type='hidden' name='" . $key . "' value='" . $val . "'/>";
            }
        }
        //submit按钮控件请不要含有name属性
        $sHtml = $sHtml . "<input type='submit' value='ok' style='display:none;''></form>";
        $sHtml = $sHtml . "<script>document.forms['alipaysubmit'].submit();</script>";
        return $sHtml;
    }

    /**
     * 获取组装好的数据
     * @return mixed
     */
    public function getCommonConfigs()
    {
        return $this->commonConfigs;
    }


    /**
     * 组装获取用户信息请求参数
     * @param $method
     * @param array $extend
     * @return $this
     * @throws ExceptionHandler
     */
    public function getUser($method, $extend = [])
    {
        //组装参数
        $commonConfigs = [
            'app_id' => $this->config->getAppId(),
            'method' => $method,
            'format' => $this->config->getFormat(),
            'charset' => $this->config->getCharset(),
            'sign_type' => $this->config->getSignType(),
            'timestamp' => date('Y-m-d H:i:s'),
            'version' => $this->config->getVersion(),
        ];

        $commonConfigs = array_merge($commonConfigs, $extend);

        if (empty($this->config->getRsaPrivateKey())) throw new ExceptionHandler('请传入私钥');
        //获取签名
        $commonConfigs['sign'] = $this->sign->generateSign($commonConfigs, $this->config->getRsaPrivateKey(), $commonConfigs['sign_type']);

        $this->commonConfigs = $commonConfigs;
        return $this;
    }


}